﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Crm.Sdk.Query;
using System.Xml.Serialization;
using System.Collections;

namespace Streamsol.Crm.XrmDevelopmentToolkit
{
    //[XmlType(Namespace = "http://schemas.microsoft.com/crm/2006/Query")]
    //[XmlSerializerAssembly("Streamsol.Crm.XmlSerializers")]
    //[XmlRoot("ColumnSet", Namespace = "http://schemas.microsoft.com/crm/2006/Query")]
    public class XrmMappedColumnSet 
    {
        private ArrayList _attributes = new ArrayList();

        //[XmlArray]
        //[XmlArrayItem(ElementName = "Attribute", IsNullable = false, Type = typeof(String))]
        public ArrayList Attributes { get { return _attributes; } }
        //[XmlIgnore]
        public string EntityName { get; set; }

        public XrmMappedColumnSet()
        { }

        public XrmMappedColumnSet(params string[] attributes)
        {
            _attributes.AddRange(attributes);
        }

        public XrmMappedColumnSet(IXrmEntity entity)
            : this(entity.GetXrmMappedFields().Select(s => s.Key).ToArray())
        { }

        public void Accept(IQueryVisitor visitor)
        {
            visitor.Visit(new ColumnSet((string[])_attributes.ToArray(typeof(string))));
        }

        public void AddColumn(string attributeName)
        {
            _attributes.Add(attributeName);
        }

        public void AddColumns(params string[] attributeNames)
        {
            _attributes.AddRange(attributeNames);
        }

        public void RemoveAllColumns()
        {
            _attributes.Clear();
        }

        public void RemoveColumn(string name)
        {
            _attributes.Remove(name);
        }
                
        public static implicit operator ColumnSet(XrmMappedColumnSet columnSet)
        {
            return new ColumnSet((string[])columnSet.Attributes.ToArray(typeof(string)));
        }
    }
}
